<template>
  <div id="tableHeaderSeach">
    <el-card :body-style="{ padding: '10px' }" shadow="never">
      <template #header>
        <div class="wrapper">
          <el-tooltip
            class="item"
            effect="dark"
            :content="showArrow ? '点击展开/收起查询条件' : title"
            placement="top"
          >
            <el-button type="text" @click="collapsed">
              {{ title
              }}<i
                v-if="showArrow"
                :class="
                  showSearchContent
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              ></i
            ></el-button>
          </el-tooltip>
          <div class="left-wrapper">
            <slot name="left"></slot>
          </div>
          <div class="flex-sub"></div>
          <div class="right-wrapper">
            <slot name="right"></slot>
            <el-button
              type="success"
              size="mini"
              :icon="RefreshIcon"
              @click="reset"
              >重置</el-button
            >
            <el-button
              type="primary"
              size="mini"
              :icon="SearchIcon"
              @click="search"
              >搜索</el-button
            >
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <div v-show="collapsedState">
          <div class="van-page-search-form">
            <div
              v-for="(form, index) in searchFormList.arr"
              :key="index + 'searchFormList.arr'"
            >
              <el-form ref="searchForm" :model="form" size="mini">
                <el-row :gutter="20" class="flex" style="flex-wrap: wrap">
                  <el-col :span="6">
                    <el-form-item prop="columnName">
                      <el-select
                        v-model="form.columnName"
                        placeholder="请选择属性名称"
                        style="width: 100%"
                        @change="(val) => handleChange(val, index)"
                      >
                        <el-option
                          v-for="(option, idx) in searchOptions.arr"
                          :key="idx + 'attributeId'"
                          :label="option.propName"
                          :value="option.columnName"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="2">
                    <el-form-item prop="operation">
                      <el-select
                        v-model="form.operation"
                        placeholder="请选择"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="(option, idx) in computeOptions"
                          :key="idx + 'operation'"
                          :label="option.label"
                          :value="option.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item prop="content">
                      <!-- 输入框 -->
                      <el-input
                        v-if="form.dataType === 'Input' || !form.dataType"
                        v-model="form.content"
                        placeholder="请输入"
                        clearable
                      />
                      <!-- 下拉选择 / 多选 / 单选 -->
                      <el-select
                        v-if="form.dataType === 'Select'"
                        v-model="form.content"
                        style="width: 100%"
                        placeholder="请选择"
                        @change="(val) => getHandleChange(val, form)"
                        filterable
                        clearable
                      >
                        <el-option
                          v-for="(option, index) in form.options"
                          :key="index"
                          :label="option.label"
                          :value="option.value"
                        >
                        </el-option>
                      </el-select>
                      <!-- 日期选择器 -->
                      <el-date-picker
                        v-if="form.dataType === 'Date'"
                        v-model="form.content"
                        type="date"
                        style="width: 100%"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择日期"
                        clearable
                      />
                      <!-- 日期时间选择器 -->
                      <el-date-picker
                        style="width: 100%"
                        v-if="form.dataType === 'DateRange'"
                        v-model="form.content"
                        type="daterange"
                        value-format="YYYY-MM-DD"
                        @change="(val) => getHandleChange(val, form)"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                      >
                      </el-date-picker>
                      <!-- 月日选择器 -->
                      <el-date-picker
                        v-if="form.dataType === 'Month'"
                        v-model="form.content"
                        type="month"
                        style="width: 100%"
                        value-format="timestamp"
                        placeholder="请选择月"
                        clearable
                      />
                      <!-- 数字查询 -->
                      <el-input-number
                        v-if="form.dataType === 'Number'"
                        v-model="form.content"
                        placeholder="请输入"
                        style="width: 100%"
                      ></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="2">
                    <el-form-item prop="relationExpression">
                      <el-select
                        v-model="form.relationExpression"
                        placeholder="请选择"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="(option, idx) in relationOptions"
                          :key="idx + 'relationExpression'"
                          :label="option.label"
                          :value="option.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item class="tl">
                      <el-button
                        v-if="index === searchFormList.arr.length - 1"
                        type="primary"
                        size="mini"
                        @click="handleAdd()"
                        >新增
                      </el-button>
                      <el-button
                        v-if="searchFormList.arr.length > 1"
                        type="danger"
                        size="mini"
                        @click="handleRemove(index)"
                        >删除
                      </el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </div>
      </el-collapse-transition>
    </el-card>
  </div>
</template>

<script lang="ts">
import { getQueryData } from "@/api/url";
import { post } from "@/api/http";
import { ObjData } from "@/components/types";
import {
  computed,
  inject,
  nextTick,
  onMounted,
  ref,
  reactive,
  defineComponent,
  PropType,
} from "vue";
import {
  Search as SearchIcon,
  Refresh as RefreshIcon,
} from "@element-plus/icons";

export default defineComponent({
  props: {
    title: {
      type: String,
      default: "查询条件",
    },
    canCollapsed: {
      type: Boolean,
      default: false,
    },
    searchModel: {
      type: Array as PropType<Array<FormItem>>,
      default: null,
    },
    defaultCollapsedState: {
      type: Boolean,
      default: true,
    },
    queryCode: {
      type: String,
      default: "",
    },
  },
  emits: ["searchForm"],
  setup(props, { emit }) {
    const showSearchContent = ref(props.defaultCollapsedState);
    const showArrow = computed(() => {
      return (
        props.canCollapsed &&
        !!props.searchModel &&
        props.searchModel.length !== 0
      );
    });
    let searchFormList = reactive({
      arr: [] as any,
    });
    let searchOptions = reactive({
      arr: [] as any,
    });
    let filterProps = reactive({
      arr: [] as any,
    });
    let searchFormSpecial = reactive({
      arr: [] as any,
    });
    const computeOptions = reactive([
      {
        label: "等于",
        value: "=",
      },
      {
        label: "小于",
        value: "<",
      },
      {
        label: "大于",
        value: ">",
      },
      {
        label: "大于等于",
        value: ">=",
      },
      {
        label: "小于等于",
        value: "<=",
      },
      {
        label: "不包含",
        value: "not like",
      },
      {
        label: "包含",
        value: "like",
      },
    ]);
    const relationOptions = reactive([
      {
        label: "或者",
        value: "or",
      },
      {
        label: "并且",
        value: "and",
      },
    ]);
    const searchAttributes = reactive([
      "columnName",
      "operation",
      "content",
      "relationExpression",
    ]); // 需要提交的属性
    const collapsedState = computed(() => {
      return showSearchContent.value;
    });
    function collapsed() {
      showSearchContent.value = !showSearchContent.value;
    }
    function getQuery() {
      post({
        url: getQueryData,
        data: { code: props.queryCode },
      })
        .then((res: any) => {
          searchOptions.arr = res.resultList;
          console.log(searchOptions.arr, 1212);
          if (searchOptions.arr.length) {
            searchOptions.arr.forEach(
              (item: { dataType: string; options: any; content: string }) => {
                if (item.dataType === "Select") {
                  item.options = JSON.parse(item.content);
                }
              }
            );
          }
        })
        .catch(console.log);
    }
    function search() {
      const paramsList = [] as any;
      searchFormList.arr.forEach((searchForm: { [x: string]: any }) => {
        if (['Input','Date','Select'].includes(searchForm.dataType)) {
          const params = {} as any;
          searchAttributes.forEach((item) => {
            if (searchForm[item]) {
              params[item] = searchForm[item];
            }
          });
          const boolArr = [];
          // eslint-disable-next-line guard-for-in
          for (const key in params) {
            let bool = false;
            if (params[key]) {
              bool = true;
            } else {
              bool = false;
            }
            boolArr.push(bool);
          }

          if (boolArr.length === Object.keys(searchAttributes).length) {
            paramsList.push(params);
          }
        }
      });
      if (searchFormSpecial.arr.length > 0) {
        paramsList.push(...searchFormSpecial.arr);
      }
      if (paramsList.length > 0) {
        emit("searchForm", paramsList);
      }
    }
    function reset() {
      searchFormList.arr = [];
      handleAdd();
      emit("searchForm", null);
    }
    function handleChange(val: any, index: string | number) {
      const currentItem: any[] = searchOptions.arr.filter(
        (item: any) => item.columnName === val
      );
      searchFormList.arr[index]["dataType"] =
        currentItem[0]?.dataType || "Input";
      searchFormList.arr[index]["operation"] = "=";
      searchFormList.arr[index]["relationExpression"] = "and";
      searchFormList.arr[index]["content"] = "";
      searchFormList.arr[index]["options"] = currentItem[0]?.options;
    }
    function getHandleChange(
      val: string | any[],
      item: { columnName: any; changeCallback: any; dataType: any }
    ) {
      const { columnName: prop, changeCallback, dataType } = item;

      // 如果有 change 联动
      if (changeCallback) {
        // this.__assignRelatedOptions(item, val);
      }
      // 特殊类型处理
      if (
        ["DateRange", "DatetimeRange", "SelectTree", "Select"].includes(
          dataType
        )
      ) {
        !filterProps.arr.includes(prop) && filterProps.arr.push(prop);
        // 时间范围
        if (["DateRange", "DatetimeRange"].includes(dataType)) {
          if (val?.length > 0) {
            let propRange = [];
            if (prop.includes("[")) {
              propRange = JSON.parse(prop);
            } else {
              propRange = [prop, prop];
            }
            searchFormSpecial.arr.push({
              operation: ">=",
              relationExpression: "and",
              columnName: propRange[0],
              content: val && val[0],
            });
            searchFormSpecial.arr.push({
              operation: "<=",
              relationExpression: "and",
              columnName: propRange[1],
              content: val && val[1],
            });
          } else {
            searchFormSpecial.arr = [];
          }
        }
        
      }
    }
    function handleAdd() {
      searchFormList.arr.push({
        columnName: "",
        operation: "=",
        relationExpression: "and",
        dataType: "Input",
        content: "",
      });
    }
    function handleRemove(index: any) {
      searchFormList.arr.splice(index, 1);
    }
    onMounted(() => {
      getQuery();
      if (searchFormList.arr.length === 0) {
        handleAdd();
      }
      console.log(searchFormList.arr, 1212);
    });
    return {
      showSearchContent,
      showArrow,
      collapsedState,
      collapsed,
      SearchIcon,
      RefreshIcon,
      searchFormList,
      searchOptions,
      computeOptions,
      relationOptions,
      searchAttributes,
      getQuery,
      search,
      reset,
      handleChange,
      handleAdd,
      handleRemove,
      getHandleChange,
    };
  },
});
</script>

<style lang="scss">
#tableHeaderSeach {
  margin-bottom: 10px;
  .el-card .el-card__header {
    padding: 0px 10px;
  }
  .wrapper {
    display: flex;
    flex-direction: row;
    align-items: center;
    .left-wrapper {
      margin-left: 5px;
    }
  }
  .search-content-wrapper {
    padding: 10px;
    .search-item-wrapper {
      justify-content: center;
      align-items: center;
      & > span {
        color: #606266;
        font-size: 14px;
        font-weight: 500;
        margin-right: 8px;
      }
      .form-item {
        flex: 1;
      }
    }
  }
}
</style>
